import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Element from 'element-ui'
import "element-ui/lib/theme-chalk/index.css"
import axios from 'axios'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import 'github-markdown-css';
import myStorage from "./utils/myStorage";
import Cookies from 'js-cookie'//cookie插件
import iView from 'iview';
import 'iview/dist/styles/iview.css';
// 全局函数及变量
import Global from './Global';
Vue.config.productionTip = false

Vue.use(Element)
Vue.use(mavonEditor)
Vue.use(Global);
Vue.use(myStorage);
Vue.use(iView);


//全局组件
import Login from "./components/Login";
import Regist from "./components/Regist";
import GoodsList from "./components/GoodsList";
import HomeGoodsList from "./components/HomeGoodsList";
Vue.component(Login.name, Login);
Vue.component(Regist.name, Regist);
Vue.component(GoodsList.name, GoodsList);
Vue.component(HomeGoodsList.name, HomeGoodsList);
//全局组件END



//时间格式化插件
import Moment from 'moment'
// 定义全局时间戳过滤器
Vue.filter('formatDate', function(value) {
    return Moment(value).format('YYYY-MM-DD HH:mm')
})

//axios请求配置
axios.defaults.headers.post['Content-Type'] = 'application/json';
Vue.prototype.$axios = axios;
axios.defaults.baseURL = "/api";


// 全局拦截器,在进入需要用户权限的页面前校验是否已经登录
router.beforeResolve((to, from, next) => {
    const loginUser = myStorage.getItem('user');
    // 判断路由是否设置相应校验用户权限
    if (to.meta.requireAuth) {
        if (!loginUser) {
            // 没有登录，显示登录组件
            store.dispatch("setShowLogin", true);
            if (from.name == null) {
                next("/");
                return;
            }
            // 终止导航
            next(false);
            return;
        }
    }
    next();
});

// 全局请求拦截器
// axios.interceptors.request.use(
//     config => {
//         return config;
//     },
//     error => {
//         // 跳转error页面
//         router.push({ path: "/error" });
//         return Promise.reject(error);
//     }
// );

// 全局响应拦截器
axios.interceptors.response.use(
    res => {
        if (res.data.code === "500") {
            // 500服务器异常 跳转error页面
            router.push({ path: "/error" });
        }
        return res;
    },
    error => {
        // 跳转error页面
        router.push({ path: "/error" });
        return Promise.reject(error);
    }
);

// 跳转后返回顶部
router.afterEach((to, from, next) => {
    window.scrollTo(0, 0);
})


new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
